package com.example.rabbitmq.demon1;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RabbitProducer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //创建工厂连接
        ConnectionFactory connectionFactory=new ConnectionFactory();
        //设置参数
        connectionFactory.setHost("124.220.134.59");
        connectionFactory.setPort(15672);
        connectionFactory.setVirtualHost("study");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        //创建connection连接
        Connection connection=connectionFactory.newConnection();
        //创建管道
        Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare("hello",true,false,false,null);
        String msg = "Hello World";
        channel.basicPublish("", "hello", null, msg.getBytes());
        System.out.println(msg + "消息发送成功");
        channel.close();
        connection.close();
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息: " + new String(body));
            }
        };
        channel.basicConsume("hello", true, consumer);
        //等待回调函数执行完毕之后, 关闭资源
        TimeUnit.SECONDS.sleep(5);
        channel.close();
        connection.close();

    }

}
